<template>
  <div>
    <el-select @change="changeTheme" v-model="t">
      <el-option v-for="(v,i) in theme" :key="i" :label="v.name" :value="v.value"></el-option>
    </el-select>
    <div id="chart" style="width:600px;height:400px">
    </div>
  </div>
</template>

<script>
import { debounce } from "@/utils";
export default {
  name: "chart",
  props: {
    datas: {
      type: Array
    },
    names: {
      type: Array
    },
    width: {
      type: String,
      default: "500px"
    },
    height: {
      type: String,
      default: "300px"
    }
  },
  watch: {
    datas: {
      deep: true,
      handler(val) {
        this.initChart(val, this.names);
      }
    }
  },
  data() {
    return {
      chart: "",
      t:'infographic',
      theme:[
        {
          value:'infographic',
          name:'infographic'
        },
        {
          value:'vintage',
          name:'vintage'
        },
        {
          value:'macarons',
          name:'macarons'
        },
        {
          value:'roma',
          name:'roma'
        },
        {
          value:'shine',
          name:'shine'
        }
      ]
    };
  },
  methods: {
    changeTheme(val){
      this.chart.dispose();
      this.chart = null;
      this.initChart(this.datas, this.names);
    },
    initChart(datas, legendName) {
      this.chart = echarts.init(document.getElementById("chart"),this.t);
      this.chart.setOption({
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
          left: "center",
          bottom: "10",
          data: legendName
        },
        calculable: true,
        series: [
          {
            name: "WEEKLY WRITE ARTICLES",
            type: "pie",
            roseType: "radius",
            radius: [15, 95],
            center: ["50%", "38%"],
            data: datas,
            animationEasing: "cubicInOut",
            animationDuration: 2600
          }
        ]
      });
    }
  },
  mounted() {
    this.initChart(this.datas, this.names);
    this.__resizeHanlder = debounce(() => {
      if (this.chart) {
        this.chart.resize();
      }
    }, 100);
    window.addEventListener("resize", this.__resizeHanlder);
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    window.removeEventListener("resize", this.__resizeHanlder);
    this.chart.dispose();
    this.chart = null;
  }
};
</script>

<style scoped>

</style>
